<?php

namespace app\model\system;

use albert\traits\ModelTrait;
use app\model\BaseModel;
use albert\services\FormBuilder;
use FormBuilder\exception\FormBuilderException;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;

/**
 * 系统配置 Model
 * Class SystemConfig
 * @package app\models\system
 */
class SystemConfig extends BaseModel
{
    use ModelTrait;

    /**
     * 选择文本框类型
     * Author: Albert3306
     * Date: 2021/7/2
     * @return array
     */
    public static function textType(): array
    {
        return [
            ['value' => 'input', 'label' => '文本框'],
            ['value' => 'dateTime', 'label' => '时间'],
            ['value' => 'color', 'label' => '颜色'],
            ['value' => 'number', 'label' => '数字']
        ];
    }

    /**
     * 选择文文件类型
     * Author: Albert3306
     * Date: 2021/7/2
     * @return array
     */
    public static function uploadType(): array
    {
        return [
            ['value' => 1, 'label' => '单图'],
            ['value' => 2, 'label' => '多图'],
            ['value' => 3, 'label' => '文件']
        ];
    }

    /**
     * 初始化查询条件
     * Author: Albert3306
     * Date: 2021/6/30
     * @param $where
     * @param null $model
     * @return SystemConfig|mixed
     */
    public static function initWhere($where, $model = null)
    {
        $model = $model ?? new self;
        if (isset($where['name']) && $where['name'] !== '') {
            $model = $model->where('name', $where['name']);
        }
        if (isset($where['inName']) && $where['inName'] !== '') {
            $model = $model->whereIn('name', $where['inName']);
        }
        if (isset($where['status']) && $where['status'] !== '') {
            $model = $model->where('status', $where['status']);
        }
        if (isset($where['config_tab_id']) && $where['config_tab_id'] !== '') {
            $model = $model->where('config_tab_id', $where['config_tab_id']);
        }
        return $model;
    }

    /**
     * 获取知道分类下的所有配置字段
     * Author: Albert3306
     * Date: 2021/6/30
     * @param $tab_id
     * @param int $status
     * @return Collection
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getAll($tab_id, int $status = 1): Collection
    {
        $where['config_tab_id'] = $tab_id;
        if ($status == 1) $where['status'] = $status;
        return self::initWhere($where)->order('sort desc,id asc')->select();
    }

    /**
     * 获取一数据
     * Author: Albert3306
     * Date: 2021/7/2
     * @param $filed
     * @param $value
     * @return array|Model|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getOneConfig($filed, $value)
    {
        $where[$filed] = $value;
        return self::initWhere($where)->find();
    }

    /**
     * 文本框
     * Author: Albert3306
     * Date: 2021/7/2
     * @param $f
     */
    public static function createInputRule(&$f)
    {
        $f[] = FormBuilder::hidden('type', 'text');
        $f[] = FormBuilder::select('input_type', '类型')->setOptions(self::textType());
        $f[] = FormBuilder::input('value', '默认值');
        $f[] = FormBuilder::number('width', '文本框宽(%)', 100);
        $f[] = FormBuilder::input('required', '验证规则')->placeholder('多个请用,隔开例如：required:true,url:true');
    }

    /**
     * 多行文本框
     * Author: Albert3306
     * Date: 2021/6/30
     * @param $f
     */
    public static function createTextAreaRule(&$f)
    {
        $f[] = FormBuilder::hidden('type', 'textarea');
        $f[] = FormBuilder::textarea('value', '默认值');
        $f[] = FormBuilder::number('width', '文本框宽(%)', 100);
        $f[] = FormBuilder::number('high', '多行文本框高(%)', 5);
    }

    /**
     * 单选按钮
     * Author: Albert3306
     * Date: 2021/6/30
     * @param $f
     */
    public static function createRadioRule(&$f)
    {
        $f[] = FormBuilder::hidden('type', 'radio');
        $f[] = FormBuilder::textarea('parameter', '配置参数')->placeholder("参数方式例如:\n1=>男\n2=>女\n3=>保密");
        $f[] = FormBuilder::input('value', '默认值');
    }

    /**
     * 文件上传
     * Author: Albert3306
     * Date: 2021/7/2
     * @param $f
     * @throws FormBuilderException
     */
    public static function createUploadRule(&$f)
    {
        $f[] = FormBuilder::hidden('type', 'upload');
        $f[] = FormBuilder::radio('upload_type', '上传类型', 1)->options(self::uploadType());
    }

    /**
     * 多选框
     * Author: Albert3306
     * Date: 2021/7/2
     * @param $f
     */
    public static function createCheckboxRule(&$f)
    {
        $f[] = FormBuilder::hidden('type', 'checkbox');
        $f[] = FormBuilder::textarea('parameter', '配置参数')->placeholder("参数方式例如:\n1=>白色\n2=>红色\n3=>黑色");
    }

    /**
     * 下拉框
     * Author: Albert3306
     * Date: 2021/7/2
     * @param $f
     */
    public static function createSelectRule(&$f)
    {
        $f[] = FormBuilder::hidden('type', 'select');
        $f[] = FormBuilder::textarea('parameter', '配置参数')->placeholder("参数方式例如:\n1=>白色\n2=>红色\n3=>黑色");
    }

    /**
     * 字段状态
     * Author: Albert3306
     * Date: 2021/7/2
     * @return array[]
     */
    public static function formStatus(): array
    {
        return [['value' => 1, 'label' => '显示'], ['value' => 2, 'label' => '隐藏']];
    }

    /**
     * text  判断
     * Author: Albert3306
     * Date: 2021/7/2
     * @param $data
     * @return bool
     */
    public static function validDateTextRole($data): bool
    {
        if (!$data['width']) return self::setErrorInfo('请输入文本框的宽度');
        if ($data['width'] <= 0) return self::setErrorInfo('请输入正确的文本框的宽度');
        return true;
    }

    /**
     * textarea  判断
     * Author: Albert3306
     * Date: 2021/7/2
     * @param $data
     * @return bool
     */
    public static function validDateTextareaRole($data): bool
    {
        if (!$data['width']) return self::setErrorInfo('请输入多行文本框的宽度！');
        if (!$data['high']) return self::setErrorInfo('请输入多行文本框的高度！');
        if ($data['width'] < 0) return self::setErrorInfo('请输入正确的多行文本框的宽度！');
        if ($data['high'] < 0) return self::setErrorInfo('请输入正确的多行文本框的宽度！');
        return true;
    }

    /**
     * radio 和 checkbox规则的判断
     * Author: Albert3306
     * Date: 2021/7/2
     * @param $data
     * @return bool
     */
    public static function validDateRadioAndCheckbox($data): bool
    {
        $option = [];
        $option_new = [];
        $data['parameter'] = str_replace("\r\n", "\n", $data['parameter']); // 防止不兼容
        $parameter = explode("\n", $data['parameter']);
        if (count($parameter) < 2) return self::setErrorInfo('请输入正确格式的配置参数！');
        foreach ($parameter as $k => $v) {
            if (isset($v) && !empty($v)) {
                $option[$k] = explode('=>', $v);
            }
        }
        if (count($option) < 2) return self::setErrorInfo('请输入正确格式的配置参数！');
        $bool = 1;
        foreach ($option as $k => $v) {
            $option_new[$k] = $v[0];
            foreach ($v as $vv) {
                $vv_num = strlen($vv);
                if (!$vv_num) {
                    $bool = 0;
                }
            }
        }
        if (!$bool) return self::setErrorInfo('请输入正确格式的配置参数！');
        $num1 = count($option_new); // 提取该数组的数目
        $arr2 = array_unique($option_new); // 合并相同的元素
        $num2 = count($arr2); // 提取合并后数组个数
        if ($num1 > $num2) return self::setErrorInfo('请输入正确格式的配置参数！');
        return true;
    }

    /**
     * 获取单个参数配置
     * Author: Albert3306
     * Date: 2021/7/2
     * @param $menu
     * @return bool|mixed
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getConfigValue($menu)
    {
        if (empty($menu) || !($config_one = self::initWhere(['name' => $menu])->find())) return false;
        return json_decode($config_one['value'], true);
    }

    /**
     * 获得多个参数
     * Author: Albert3306
     * Date: 2021/7/2
     * @param $menus
     * @return array
     */
    public static function getMore($menus): array
    {
        $list = self::initWhere(['inName' => $menus])->column('value', 'menu_name') ?: [];
        foreach ($list as $menu => $value) {
            $list[$menu] = json_decode($value, true);
        }
        return $list;
    }

    /**
     * 获取所有配置
     * Author: Albert3306
     * Date: 2021/7/2
     * @return array
     */
    public static function getAllConfig(): array
    {
        $list = self::initWhere([])->column('value', 'name') ?: [];
        foreach ($list as $menu => $value) {
            $list[$menu] = json_decode($value, true);
        }
        return $list;
    }

    /**
     * 处理
     * Author: Albert3306
     * Date: 2021/7/2
     * @param $data
     * @return array
     */
    public static function tidyConfigTab($data): array
    {
        return [
            'id'   => $data['id'],
            'pid'  => $data['pid'],
            'type' => $data['type'],
            'icon' => $data['icon'],
            'label'=> $data['title'],
        ];
    }

    /**
     * 获取所有配置分类
     * Author: Albert3306
     * Date: 2021/7/2
     * @param int $type
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getConfigTabAll(int $type = 0): array
    {
        $configAll = SystemConfigTab::getAll($type);
        $config_tab = [];
        foreach ($configAll as $k => $v) {
            if (!$v['info']) {
                $config_tab[$k] = self::tidyConfigTab($v);
            }
        }
        return $config_tab;
    }

    /**
     * 获取所有子配置分类
     * @param int $pid
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getConfigChildrenTabAll(int $pid = 0): array
    {
        $configAll = SystemConfigTab::getChildrenTab($pid);
        $config_tab = [];
        foreach ($configAll as $k => $v) {
            if (!$v['info']) {
                $config_tab[$k] = self::tidyConfigTab($v);
            }
        }
        return $config_tab;
    }

    /**
     * 生成配置表单
     * @param $list
     * @return array
     * @throws FormBuilderException
     */
    public static function builder_config_from_data($list): array
    {
        $f = [];
        foreach ($list as $data) {
            switch ($data['type']) {
                case 'text': // 文本框
                    switch ($data['input_type']) {
                        case 'number':
                            $data['value'] = json_decode($data['value'], true) ?: 0;
                            $f[] = FormBuilder::number($data['name'], $data['info'], $data['value'])->info($data['desc']);
                            break;
                        case 'dateTime':
                            $f[] = FormBuilder::dateTime($data['name'], $data['info'], $data['value'])->info($data['desc']);
                            break;
                        case 'color':
                            $data['value'] = json_decode($data['value'], true) ?: '';
                            $f[] = FormBuilder::color($data['name'], $data['info'], $data['value'])->info($data['desc']);
                            break;
                        default:
                            $data['value'] = json_decode($data['value'], true) ?: '';
                            $f[] = FormBuilder::input($data['name'], $data['info'], $data['value'])->info($data['desc'])->placeholder($data['desc'])->col(13);
                            break;
                    }
                    break;
                case 'textarea': // 多行文本框
                    $data['value'] = json_decode($data['value'], true) ?: '';
                    $f[] = FormBuilder::textarea($data['name'], $data['info'], $data['value'])->placeholder($data['desc'])->info($data['desc'])->rows(6)->col(13);
                    break;
                case 'radio': // 单选框
                    $data['value'] = json_decode($data['value'], true) ?: '0';
                    $parameter = explode("\n", $data['parameter']);
                    $options = [];
                    if ($parameter) {
                        foreach ($parameter as $v) {
                            $pData = explode("=>", $v);
                            $options[] = ['label' => $pData[1], 'value' => $pData[0]];
                        }
                        $f[] = FormBuilder::radio($data['name'], $data['info'], $data['value'])->options($options)->info($data['desc'])->col(13);
                    }
                    break;
                case 'upload': // 文件上传
                    switch ($data['upload_type']) {
                        case 1:
                            $data['value'] = json_decode($data['value'], true) ?: '';
                            $f[] = FormBuilder::frameImageOne($data['name'], $data['info'], '/admin/widget/images?fodder=' . $data['name'], $data['value'])->icon('image')->width('70%')->height('500px')->info($data['desc'])->col(13);
                            break;
                        case 2:
                            $data['value'] = json_decode($data['value'], true) ?: [];
                            $f[] = FormBuilder::frameImages($data['name'], $data['info'], '/admin/widget/images?fodder=' . $data['name'], $data['value'])->maxLength(5)->icon('image')->width('70%')->height('500px')->info($data['desc'])->col(13);
                            break;
                        case 3:
                            $data['value'] = json_decode($data['value'], true);
                            $f[] = FormBuilder::uploadFileOne($data['name'], $data['info'], '/admin/system/config/upload', $data['value'])->name('file')->info($data['desc'])->col(13);
                            break;
                    }

                    break;
                case 'checkbox': // 多选框
                    $data['value'] = json_decode($data['value'], true) ?: [];
                    $parameter = explode("\n", $data['parameter']);
                    $options = [];
                    if ($parameter) {
                        foreach ($parameter as $v) {
                            $pData = explode("=>", $v);
                            $options[] = ['label' => $pData[1], 'value' => $pData[0]];
                        }
                        $f[] = FormBuilder::checkbox($data['name'], $data['info'], $data['value'])->options($options)->info($data['desc'])->col(13);
                    }
                    break;
                case 'select': // 多选框
                    $data['value'] = json_decode($data['value'], true) ?: [];
                    $parameter = explode("\n", $data['parameter']);
                    $options = [];
                    if ($parameter) {
                        foreach ($parameter as $v) {
                            $pData = explode("=>", $v);
                            $options[] = ['label' => $pData[1], 'value' => $pData[0]];
                        }
                        $f[] = FormBuilder::select($data['name'], $data['info'], $data['value'])->options($options)->info($data['desc'])->col(13);
                    }
                    break;
            }
        }
        return $f;
    }
}